// mircoApp/productIndex/productIndex.js
var app = getApp();
import util from "../../utils/util";
const skinBehavior = require("../../utils/themeSkin/skinBehavior");
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    query:{
      keyword:'',
      filter_ids:'',
      page:1,
      basic_info:1
    },
    tagList:[],
    tagIndex:[],
    goodsList:[],
    isLoadMore: true,
    totalPage: 0,
    timer: "", //防抖时间
    coThemeColor:'',
    productShow:false,
    tagHeight:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initData();
    this.getTagData();
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  colorFin(a) { //处理主题色
    a = a.substring(1);
    a = a.toLowerCase();
    let b = new Array();
    for (let x = 0; x < 3; x++) {
      b[0] = a.substr(x * 2, 2);
      b[3] = "0123456789abcdef";
      b[1] = b[0].substr(0, 1);
      b[2] = b[0].substr(1, 1);
      b[20 + x] = b[3].indexOf(b[1]) * 16 + b[3].indexOf(b[2]);
    }
    return b[20] + "," + b[21] + "," + b[22];
  },
  goodsTo(e) {
    let id = e.currentTarget.dataset.item.id;
    wx.navigateTo({
      url: `/packageA/detail_v2/detail_v2?id=${id}`
    });
  },
  productBtn() {
    this.setData({
      productShow:!this.data.productShow
    })
  },
  listChildBtn(event) {
    let {index} =event.currentTarget.dataset;
    const query = wx.createSelectorQuery();
    this.data.tagList[index].heightChecked = !this.data.tagList[index].heightChecked
    this.setData({
      tagList:this.data.tagList
    })
    this.data.tagHeight = 0;
    if(this.data.tagList.length > 4) { //处理超过4个标签显示还是隐藏
      setTimeout(() => { //没有定时器，执行顺序会比接口快
        query.selectAll(".tag-box").boundingClientRect(rect => {
          if (rect && rect.length > 0) {
            rect.map((item,index) => {
              console.log(item.height);
              if(index < 4) {
                this.data.tagHeight += item.height
              }
            })
            this.setData({
              tagHeight:this.data.tagHeight
            })
            console.log(this.data.tagHeight);
          }
        }).exec();
      },100)
    } 
  },
  tagClick(event) {
    let {itemchild,index,indexchild} =event.currentTarget.dataset;
    let childArr = [];
    if(itemchild.id) { //其他标签是多选的
      this.data.tagList[index].value[indexchild].checked = !this.data.tagList[index].value[indexchild].checked;
      this.data.tagList[index].value[0].checked = false;
    } else {
      this.data.tagList[index].value.map((item,index) => { //如果选择全部的话，其他标签不选择
        item.checked = false;
      })
      this.data.tagList[index].value[0].checked = true;
    }
    this.data.tagList.map((item,index) => {
      item.value.map((childItem,childIndex) => {
        if(childItem.checked) {
          childArr.push(childItem.id);
        }
      })
    })
    let arrId = childArr.filter((item,index) =>  item != '' || item != 0);
    this.data.query.filter_ids = arrId.join(',');
    this.data.query.page = 1;
    this.data.isLoadMore = true;
    this.setData({
      tagList:this.data.tagList
    })
    this.getData();
  },
  initData() {
    this.setData({
      tagHeight:0,
      isLoadMore:true,
      productShow:false,
      'query.keyword':'',
      'query.filter_ids':'',
      'query.page':1,
      tagList:[],
      tagIndex:[],
      goodsList:[],
      tagHeightArr:[],
      tagChildArr:[]
    })
  },
  searchChange({ detail }) {
    this.setData({ 
      'query.keyword': detail,
      'query.page':1,
      isLoadMore:true,
    });
    // 防抖
    if (this.data.timer) clearTimeout(this.data.timer);
    this.data.timer = setTimeout(() => {
      util.debounce(this.getData());
    }, 500);
  },
  //获取产品标签数据
  getTagData() {
    let that = this;
    let urlStr = app.getNetAddresss("goods.goods.get-tag-goods-list");
    app._getNetWork({
      url: urlStr,
      data:{basic_info:1},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let themeColor = res.basic_info?.theme_color;
          let data = res.data;
          const query = wx.createSelectorQuery();
          let tagQuery =  wx.createSelectorQuery();
          let tagQueryText =  wx.createSelectorQuery();
          this.data.coThemeColor = this.colorFin(themeColor) || this.colorFin('#F15353');
          if(data.title) {
            wx.setNavigationBarTitle({
              title: data.title
            })
          }
          if(data.tag_list.length > 0) { //遍历标签处理数据
            data.tag_list.map((item,index) => {
              item.heightChecked = false;
              item.value.map((childItem,childIndex) => {
                childItem.checked = false;
                if(childIndex == 0) {
                  childItem.checked = true;
                }
              })
            })
            
          }
          setTimeout(() => {
            tagQuery.selectAll(".tag-list-child").boundingClientRect(rect => {
              if (rect && rect.length > 0) {
                rect.map((item,index) => {
                  this.data.tagHeightArr.push({
                    height:rect[index].height,
                    tagHeight:(rect[index].height * 2) 
                  })
                });
                console.log(this.data.tagHeightArr);
                this.setData({
                  tagHeightArr:this.data.tagHeightArr
                })
              }
            }).exec();
            tagQueryText.select(".tag-item").boundingClientRect(react => {
              if(react) {
                console.log(react.height);
                this.data.tagHeightArr.forEach((item,index) => {
                  item.tagHeight = (react.height + 9) * 2
                })
                console.log(this.data.tagHeightArr);
                console.log(this.data.tagChildArr);
                this.setData(({
                  tagHeightArr:this.data.tagHeightArr
                }))
              }
            }).exec();
          },800)
          if(data.tag_list.length > 4 && !this.data.tagHeight) { //处理超过4个标签显示还是隐藏
            setTimeout(() => { //没有定时器，执行顺序会比接口快
              query.selectAll(".tag-box").boundingClientRect(rect => {
                if (rect && rect.length > 0) {
                  rect.map((item,index) => {
                    console.log(item.height);
                    if(index < 4) {
                      this.data.tagHeight += item.height
                    }
                  })
                  this.setData({
                    tagHeight:this.data.tagHeight
                  })
                  console.log(this.data.tagHeight);
                }
              }).exec();
            },1000)
          }
          
          
          this.setData({
            coThemeColor:this.data.coThemeColor,
            tagList:data.tag_list,
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //获取产品中心数据
  getData() {
    let that = this;
    let urlStr = app.getNetAddresss("goods.goods.search-tag-goods");
    app._getNetWork({
      url: urlStr,
      data:this.data.query,
      success: (resdata) => {
        var res = resdata.data;
        wx.hideLoading();
        wx.hideNavigationBarLoading();//隐藏导航条加载动画
        //停止下拉刷新
        wx.stopPullDownRefresh();
        if (res.result == 1) {
          let data = res.data;
          this.data.totalPage = data.last_page;
          if (!this.data.totalPage) {
            this.data.totalPage = 0;
          }
          this.setData({
            goodsList: data.data
          })
        } else {
          this.data.query.page = this.data.query.page - 1;
          this.data.isLoadMore = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //获取更多数据
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.query.page >= this.data.totalPage) {
      return;
    } else {
      this.data.query.page = this.data.query.page + 1;
      let urlStr = app.getNetAddresss("goods.goods.search-tag-goods");
      app._getNetWork({
        url: urlStr,
        data:this.data.query,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data?.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              goodsList : this.data.goodsList.concat(list),
            })
          } else {
            this.data.query.page = this.data.query.page - 1;
            this.data.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading();
     //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
     wx.showLoading({
      title: '刷新中...',
    })
    this.initData();
    this.getTagData();
    this.getData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})